{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>个人主页 - ShortVid</title>
  <!-- 与首页一致的依赖与样式 -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="{% static 'home/home.css' %}">
  <style>
    .resp { background: #f8fafc; border: 1px dashed #cbd5e1; border-radius: 10px; padding: 12px; white-space: pre-wrap; max-height: 320px; overflow: auto; }
    .card-actions { display:flex; gap:.5rem; }
  </style>
</head>
<body>
  <!-- 与首页一致的导航栏 -->
  <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm py-3">
    <div class="container">
      <a class="navbar-brand" href="{% url 'home' %}"><i class="fas fa-play-circle me-2"></i>ShortVid</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav me-auto">
          <li class="nav-item"><a class="nav-link" href="{% url 'home' %}">首页</a></li>
          <li class="nav-item"><a class="nav-link" href="{% url 'discover' %}">发现</a></li>
          <li class="nav-item"><a class="nav-link" href="{% url 'hot' %}">热门</a></li>
          <li class="nav-item"><a class="nav-link" href="{% url 'following' %}">关注</a></li>
        </ul>
        <div class="d-flex align-items-center">
          {% if user.is_authenticated %}
            <a href="{% url 'profile' %}" class="d-flex align-items-center me-3 text-decoration-none">
              <div class="user-avatar">{{ user.username|first|upper }}</div>
              <span class="user-greeting ms-2">你好, {{ user.username }}!</span>
            </a>
            <a href="{% url 'logout' %}" class="btn btn-outline-primary btn-sm">注销</a>
          {% else %}
            <a href="{% url 'login' %}" class="btn btn-outline-primary me-2">登录</a>
            <a href="{% url 'register' %}" class="btn btn-primary">注册</a>
          {% endif %}
        </div>
      </div>
    </div>
  </nav>
  <main class="py-5">
    <div class="container">
      <h2 class="section-title mb-4">个人主页</h2>

      <div class="card mb-4">
        <div class="card-body">
          <h5 class="card-title">上传视频</h5>
          <!-- 保留原有的 URL 上传方式 -->
          <div class="row g-2 align-items-center mb-2">
            <div class="col-md-6"><input id="video_url" type="text" class="form-control" placeholder="视频 URL，例如 https://example.com/video.mp4 或本地 /media/videos/xxx.mp4" /></div>
            <div class="col-md-4"><input id="video_title" type="text" class="form-control" placeholder="可选：标题" /></div>
            <div class="col-md-2 d-grid"><button id="btn_upload" class="btn btn-primary">提交到平台</button></div>
          </div>
          
          <!-- 新增：本地文件上传生成本地 URL，并自动填充到上面的输入框 -->
          <div class="row g-2 align-items-center mb-2">
            <div class="col-md-8">
              <input id="video_file" type="file" accept="video/*" class="form-control" />
            </div>
            <div class="col-md-4 d-grid d-md-flex">
              <button id="btn_upload_file" class="btn btn-outline-secondary me-2">上传本地视频并生成 URL</button>
            </div>
          </div>

          <div class="mt-3" id="local_preview_wrap" style="display:none;">
            <label class="form-label">本地视频预览</label>
            <video id="local_preview" controls style="width:100%; max-height:360px; background:#000"></video>
          </div>

          <p class="text-muted small">第一步（可选）：上传本地视频，系统会返回一个本地可访问的 URL 并自动填入文本框；第二步：点击“提交到平台”完成与后端的入库流程。</p>
          <div id="resp_upload" class="resp"></div>
        </div>
      </div>

      <div class="card mb-4">
        <div class="card-body">
          <h5 class="card-title">我的关注 / 点赞 / 收藏</h5>
          <div class="d-flex gap-2 mb-2 flex-wrap">
            <button class="btn btn-outline-secondary" id="btn_following">查看已关注的创作者</button>
            <button class="btn btn-outline-secondary" id="btn_likes">查看我的点赞视频</button>
            <button class="btn btn-outline-secondary" id="btn_favorites">查看我的收藏</button>
            <a class="btn btn-primary" href="{% url 'following' %}">进入关注页面</a>
          </div>
          <p class="text-muted small">每个查询都会向 /api/request 发送 JSON（operation=query）。返回结果在下方展示。</p>
          <div id="resp_lists" class="resp"></div>
        </div>
      </div>

      <!-- 新增：我上传的视频（通过 /api/request 查询） -->
      <div class="card mb-4">
        <div class="card-body">
          <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-2">
            <h5 class="card-title m-0">我上传的视频</h5>
            <div class="d-flex gap-2">
              <button class="btn btn-outline-primary btn-sm" id="btn_my_videos">刷新我的视频</button>
            </div>
          </div>
          <p class="text-muted small mb-3">向 <code>/api/request</code> 发送查询：{ operation: "query", table: "video", condition: { user_id: 128 } }，展示返回结果中的视频列表。</p>
          <div id="my_videos_msg" class="text-muted small mb-2"></div>
          <div id="my_videos_grid" class="row g-3">
            <!-- 动态渲染我的视频卡片 -->
          </div>
        </div>
      </div>

      <div class="card">
        <div class="card-body">
          <h5 class="card-title">最近操作回显</h5>
          <div id="log" class="resp"></div>
        </div>
      </div>
    </div>
  </main>

  <!-- 页脚（与首页一致） -->
  <footer class="footer">
    <div class="container">
      <div class="row">
        <div class="col-lg-4 mb-4">
          <h4 class="mb-4"><i class="fas fa-play-circle me-2"></i>ShortVid</h4>
          <p>发现精彩短视频，记录美好生活瞬间。加入我们的社区，一起创作、分享和发现。</p>
          <div class="social-icons mt-4">
            <a href="#"><i class="fab fa-weibo"></i></a>
            <a href="#"><i class="fab fa-weixin"></i></a>
            <a href="#"><i class="fab fa-qq"></i></a>
            <a href="#"><i class="fab fa-github"></i></a>
          </div>
        </div>
        <div class="col-lg-2 col-md-6 mb-4">
          <h5 class="mb-4">平台</h5>
          <ul class="list-unstyled">
            <li class="mb-2"><a href="{% url 'home' %}">首页</a></li>
            <li class="mb-2"><a href="{% url 'discover' %}">发现</a></li>
            <li class="mb-2"><a href="{% url 'hot' %}">热门</a></li>
            <li class="mb-2"><a href="{% url 'following' %}">关注</a></li>
          </ul>
        </div>
        <div class="col-lg-2 col-md-6 mb-4">
          <h5 class="mb-4">帮助</h5>
          <ul class="list-unstyled">
            <li class="mb-2"><a href="#">帮助中心</a></li>
            <li class="mb-2"><a href="#">使用指南</a></li>
            <li class="mb-2"><a href="#">社区准则</a></li>
            <li class="mb-2"><a href="#">联系我们</a></li>
          </ul>
        </div>
        <div class="col-lg-4 mb-4">
          <h5 class="mb-4">订阅我们的资讯</h5>
          <p>获取最新功能和活动信息</p>
          <div class="input-group mb-3">
            <input type="email" class="form-control" placeholder="请输入您的邮箱">
            <button class="btn btn-primary" type="button">订阅</button>
          </div>
        </div>
      </div>
      <hr class="my-4">
      <div class="text-center"><p>&copy; 2023 ShortVid 短视频平台. 保留所有权利.</p></div>
    </div>
  </footer>

  {{ username|json_script:"u" }}
  <script>
    let user = JSON.parse(document.getElementById('u').textContent);
    if (!user) {
      try { user = localStorage.getItem('username') || ''; } catch (e) { user = ''; }
    }
    // 同步到标题展示（如果后端未登录）
    if (user) {
      const header = document.querySelector('header div');
      if (header) header.textContent = `👤 ${user} 的个人主页`;
    }

    async function postJson(path, body) {
      try {
        const resp = await fetch(path, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(body)
        });
        const data = await resp.json().catch(() => ({ ok: false, parse_error: true }));
        return { status: resp.status, data };
      } catch (e) {
        return { status: 0, data: { ok: false, error: e?.message || 'network_error' } };
      }
    }

    function pretty(o) { try { return JSON.stringify(o, null, 2) } catch { return String(o) } }
    function log(msg, obj) {
      const box = document.getElementById('log');
      const line = `[${new Date().toLocaleTimeString()}] ${msg}\n` + (obj ? pretty(obj) : '') + '\n\n';
      box.textContent = line + box.textContent;
    }

    // 渲染“我上传的视频”到网格
    function renderMyVideos(items) {
      const grid = document.getElementById('my_videos_grid');
      const msg = document.getElementById('my_videos_msg');
      grid.innerHTML = '';
      if (!Array.isArray(items) || items.length === 0) {
        msg.textContent = '暂无数据或后端未返回列表数据。';
        return;
      }
      msg.textContent = '';
      for (const it of items) {
        const url = it.video_url || it.url;
        const title = it.title || '未命名视频';
        const up = it.upload_time ? new Date(it.upload_time).toLocaleString() : '';
        const vid = it.video_id || it.id || '';
        const col = document.createElement('div');
        col.className = 'col-12 col-sm-6 col-lg-4';
        col.innerHTML = `
          <div class="card h-100 shadow-sm">
            <div class="ratio ratio-16x9 bg-dark">
              ${url ? `<video controls preload="metadata" src="${url}" style="width:100%; height:100%;"></video>` : '<div class="d-flex align-items-center justify-content-center text-white-50">无视频地址</div>'}
            </div>
            <div class="card-body">
              <h6 class="card-title text-truncate" title="${title}">${title}</h6>
              ${up ? `<div class="text-muted small">上传时间：${up}</div>` : ''}
              ${url ? `<div class="small text-break mt-1"><span class="text-muted">URL:</span> <a href="${url}" target="_blank">${url}</a></div>` : ''}
              <div class="card-actions mt-2">
                <button class="btn btn-sm btn-outline-danger" data-action="delete" data-id="${String(vid)}" data-url="${url || ''}"><i class="fa fa-trash"></i> 删除</button>
              </div>
            </div>
          </div>
        `;
        grid.appendChild(col);
      }
    }

    // 提交到平台（使用当前 URL：可以是公网地址或本地 /media/ 地址）
    document.getElementById('btn_upload').addEventListener('click', async () => {
      const url = document.getElementById('video_url').value.trim();
      const title = document.getElementById('video_title').value.trim();
      if (!url) { alert('请输入视频 URL'); return; }
          const payload = {
        operation: 'insert',
        table: 'video',
        data: {
          video_url: url,
          title: title || null,
              user_id: "128",   // 硬编码 user_id=128，作为字符串以匹配 TEXT 外键
          upload_time: new Date().toISOString()
        }
      };
      const r = await postJson('/api/request', payload);
      document.getElementById('resp_upload').textContent = pretty(r);
      log('上传视频', payload);
    });

    // 本地文件上传 -> 返回本地 URL -> 自动填充
    document.getElementById('btn_upload_file').addEventListener('click', async () => {
      const input = document.getElementById('video_file');
      if (!input.files || !input.files.length) {
        alert('请选择一个视频文件');
        return;
      }
      const fd = new FormData();
      fd.append('file', input.files[0]);
      try {
        const resp = await fetch('/api/upload-video-file', {
          method: 'POST',
          body: fd
        });
        const data = await resp.json().catch(() => ({ ok: false, error: 'parse_error' }));
        if (!resp.ok || !data.ok) {
          document.getElementById('resp_upload').textContent = pretty({ status: resp.status, data });
          alert('上传失败：' + (data.error || resp.status));
          return;
        }
        // 自动填充 URL，并展示本地预览
        document.getElementById('video_url').value = data.url;
        const pv = document.getElementById('local_preview');
        pv.src = data.url;
        document.getElementById('local_preview_wrap').style.display = '';
        log('本地视频已上传，生成 URL', data);
      } catch (e) {
        document.getElementById('resp_upload').textContent = pretty({ ok: false, error: e?.message || 'network_error' });
      }
    });

    // 查看关注的创作者
    document.getElementById('btn_following').addEventListener('click', async () => {
      const payload = {
        operation: 'query',
        table: 'follow',
        condition: { follower: user }
      };
      const r = await postJson('/api/request', payload);
      document.getElementById('resp_lists').textContent = pretty(r);
      log('查询已关注的创作者', payload);
    });

    // 查看点赞视频
    document.getElementById('btn_likes').addEventListener('click', async () => {
      const payload = {
        operation: 'query',
        table: 'like',
        condition: { user }
      };
      const r = await postJson('/api/request', payload);
      document.getElementById('resp_lists').textContent = pretty(r);
      log('查询点赞视频', payload);
    });

    // 查看收藏
    document.getElementById('btn_favorites').addEventListener('click', async () => {
      const payload = {
        operation: 'query',
        table: 'favorite',
        condition: { user }
      };
      const r = await postJson('/api/request', payload);
      document.getElementById('resp_lists').textContent = pretty(r);
      log('查询收藏视频', payload);
    });

    // 查询“我上传的视频”
    async function fetchMyVideos() {
      // 与上方上传时的 user_id 一致，当前用演示硬编码 128
      const payload = {
        operation: 'query',
        table: 'video',
        condition: { user_id: "128" },
        fields: ['video_url', 'title', 'upload_time', 'video_id'],
        order_by: 'upload_time DESC',
        limit: 20
      };
      const r = await postJson('/api/request', payload);
      log('查询我上传的视频', payload);

      // 兼容不同的返回格式：
      // 1) { query_success: true, data: [...] }
      // 2) { QuerySuccess: true, Data: [...] }  // 后端可能使用大写字段
      // 3) { data: { rows: [...] } }
      // 4) { items: [...] }
      // 5) 单条记录对象 -> 包装为数组
      // 6) mock 回显：{ insert_success: true, received: { ... } }
      let list = [];
      const body = r && r.data ? r.data : null; // r.data 是响应体
      if (body) {
        // 优先取标准/兼容字段
        let payloadData = body.data ?? body.Data ?? body.rows ?? body.items ?? null;
        if (!payloadData && Array.isArray(body)) {
          payloadData = body; // 响应体本身就是数组
        }
        if (Array.isArray(payloadData)) {
          list = payloadData;
        } else if (payloadData) {
          list = [payloadData];
        } else if (body.received && body.received.operation === 'query' && body.received.table === 'video') {
          // 仅为回显占位，无真实数据
          list = [];
        }
      }
      renderMyVideos(list);
      const msg = document.getElementById('my_videos_msg');
      if (!Array.isArray(list) || list.length === 0) {
        msg.textContent = '未获取到视频列表。如果你正在使用 mock 后端，请配置其返回示例数据，或先通过上方“提交到平台”写入后再从真实后端查询。';
      }
    }

    document.getElementById('btn_my_videos').addEventListener('click', fetchMyVideos);
    // 页面加载后自动查询一次
    fetchMyVideos();

    // 事件委托：处理我的视频列表中的删除按钮
    document.getElementById('my_videos_grid').addEventListener('click', async (e) => {
      const btn = e.target.closest('button[data-action="delete"]');
      if (!btn) return;
      const id = (btn.getAttribute('data-id') || '').trim();
      const url = (btn.getAttribute('data-url') || '').trim();
      if (!confirm('确认删除该视频吗？这将从数据库中移除，且如为本地视频，将尝试删除本地文件。')) return;

      // 1) 删除数据库记录（通过 /api/request）
      const condition = {};
      if (id) condition.video_id = isNaN(Number(id)) ? id : Number(id);
      if (Object.keys(condition).length === 0 && url) {
        condition.video_url = url; // 后端需支持按 URL 删除，若不支持请改为按主键
      }
      // 与插入时一致，演示硬编码 user_id
      condition.user_id = 128;
      const delPayload = { operation: 'delete', table: 'video', condition };
      const dbRes = await postJson('/api/request', delPayload);
      log('删除视频（数据库）', delPayload);

      // 简单判断是否删除成功（兼容多种返回格式）
      const okDb = (() => {
        const d = dbRes && dbRes.data;
        if (!d) return false;
        if (d.delete_success === true) return true;
        if (d.ok === true && (d.affected_rows >= 0 || d.deleted >= 0)) return true;
        if (typeof d.affected_rows === 'number' && d.affected_rows >= 0) return true;
        // mock 回显时也继续执行本地删除尝试
        if (d.received && d.received.operation === 'delete') return true;
        return false;
      })();

      // 2) 如果是本地文件（/media/videos/...），尝试让后端删除磁盘文件
      let okFs = true;
      if (url && url.startsWith('/media/videos/')) {
        try {
          const resp = await fetch('/api/delete-video-file', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ url })
          });
          const d = await resp.json().catch(() => ({}));
          okFs = !!(d && d.ok);
          log('删除视频（本地文件）', { status: resp.status, data: d });
        } catch (e) {
          okFs = false;
        }
      }

      if (okDb) {
        // 刷新列表
        await fetchMyVideos();
      }
      if (!okDb) alert('数据库删除可能未成功，请检查后端日志或返回值。');
      else if (!okFs && url.startsWith('/media/videos/')) alert('数据库已删除，但本地文件删除失败，请检查服务端权限。');
    });
  </script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
  <script src="{% static 'home/home.js' %}"></script>
</body>
</html>
